// pages/cart/cart.js
const api = require('../../utils/request')
const utils = require('../../utils/util')
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartData:[],
    loading: true,
    checkedGoods: [],
    allSelected: true,
    total: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(utils.loginNow()){
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(utils.loginNow()){
      this.getUserCart()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  gotoHome(){
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  getUserCart(){
    api.get('/user/cart/queryByUser').then(res=>{
      const cartList = res
      const checkedGoods = []
      for (let index = 0; index < cartList.length; index++) {
        cartList[index].priceFormat = utils.formatPrice(cartList[index].price)
        cartList[index].thumb = utils.fileMgrUrl + cartList[index].goods.pic
        checkedGoods.push(cartList[index].id + '')
        cartList[index].selected = true
      }
      let totalPrice = cartList.reduce((total,cur)=>{
        if(cur.selected){
          return total + cur.price * cur.count
        }else{
          return total
        }
      },0)
      this.setData({
        loading: false,
        cartData: cartList,
        checkedGoods: checkedGoods,
        total: totalPrice
      })
    })
  },
  countOnChange(e){
    const count =e.detail 
    const id = e.currentTarget.dataset.gid;
    // update
    api.post(`/user/cart/update/${id}/${count}`).then(res=>{
      console.log(res)
    })
  },
  countOverlimit(e){
    const id = e.currentTarget.dataset.gid;
    if(e.detail === 'minus'){
      Dialog.confirm({
        title: '温馨提示',
        message: '确定删除这一个商品吗？',
      })
      .then(() => {
        wx.showLoading()
        api.del(`/user/cart?id=${id}`).then(_=>{
          wx.hideLoading()
          const newList = this.data.cartData.filter((item)=>{
            if(item.id !== id){
              return true
            }else{
              return false
            }
          })
          const goodsIds = [...this.data.checkedGoods]
          const idx = goodsIds.indexOf(id);
          goodsIds.splice(idx,1)
          this.setData({
            cartData: newList,
            checkedGoods: goodsIds
          })
        })
      })
      .catch(() => {
        // on cancel
        console.log('no')
      });
    }
  },
  changeGoodsStatus(e){
    const {gid,s} = e.currentTarget.dataset
    this.changeOneSelected(!s,gid)
  },
  changeAllGoodsStatus(){
    if(this.data.allSelected){
      this.changeSelected(false)
    }else{
      this.changeSelected(true)
    }
  },
  changeOneSelected(b,gid){
    const list = [...this.data.cartData]
    list.forEach(item=>{
      if(item.id === gid){
        item.selected = b
      }
    })
    const all = list.every(item=>item.selected === true)
    // selected total price
    let totalPrice = list.reduce((total,cur)=>{
      if(cur.selected){
        return total + cur.price * cur.count
      }else{
        return total
      }
    },0)
    this.setData({
      cartData: list,
      allSelected: all,
      total: totalPrice
    })
  },
  changeSelected(b){
    const list = [...this.data.cartData]
    list.forEach(item=>{
      if(b){
        item.selected = true
      }else{
        item.selected = false
      }
    })
    let totalPrice = list.reduce((total,cur)=>{
      if(cur.selected){
        return total + cur.price * cur.count
      }else{
        return total
      }
    },0)
    this.setData({
      cartData: list,
      allSelected: b,
      total: totalPrice
    })
  },
  toOrderPage(){
    // user/order/prepareCheckout?chosenAddressId=
    wx.navigateTo({
      url: '/pages/conformOrder/index',
    })
  },
  onClose(){
    console.log('onClose')
  }
})